﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace XiaLastorm.Sharpshooter
{
	/// <summary>
	/// 帮助发送和接收消息的静态类
	/// </summary>
	public static class MessageHelper
	{
		/// <summary>
		/// 发送消息
		/// </summary>
		/// <param name="socket">被操作的套接字</param>
		/// <param name="message">要发送的消息</param>
		public static void Send(Socket socket, Message message)
		{
			if (socket == null)
				throw new ArgumentNullException("socket");
			if (message == null)
				throw new ArgumentNullException("message");
			byte[] data = message.ToBytes();
			byte[] lengthBytes = BitConverter.GetBytes(data.Length);

			socket.Send(lengthBytes.Concat(data).ToArray());
		}

		/// <summary>
		/// 接收消息
		/// </summary>
		/// <param name="socket">被操作的套接字</param>
		/// <returns>收到的消息</returns>
		public static Message Receive(Socket socket)
		{
			if (socket == null)
				throw new ArgumentNullException("socket");
			byte[] lengthBytes = new byte[sizeof(int)];
			int received = socket.Receive(lengthBytes, lengthBytes.Length, SocketFlags.None);
			if (received != lengthBytes.Length)
				throw new Exception("没有收到有效的消息长度信息");
			int length = BitConverter.ToInt32(lengthBytes, 0);
			byte[] data = new byte[length];
			int totalReceived = 0;
			while (totalReceived < data.Length)
			{
				received = socket.Receive(data, totalReceived, data.Length - totalReceived, SocketFlags.None);
				if (received == 0)
				{
					throw new Exception("本次调用Receive接收到的长度为0");
				}
				totalReceived += received;
			}
			return Message.FromBytes(data);
		}

	}
}
